package com.legolas.utils;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.Set;

@Component
public class JedisUtil {

    @Resource
    JedisPool jedisPool;

    /*@Autowired
    RedisTemplate redisTemplate;*/

    private Jedis getResource(){
        return jedisPool.getResource();
    }

    public byte[] set(byte[] key,byte[] value){
        Jedis jedis = getResource();
        try {

            jedis.set(key,value);
            return value;
        } finally {
            jedis.close();
        }
    }

    /**
     *设置session超时时间，单位为秒
     * @param key
     * @param i
     */
    public void expire(byte[] key,int i){
        Jedis jedis = getResource();
        try{
            jedis.expire(key,i);
        }finally {
            jedis.close();
        }
    }

    public byte[] get(byte[] key){
        Jedis jedis = getResource();
        try {
            byte[] value = jedis.get(key);
            return value;
        } finally {
            jedis.close();
        }
    }

    public void delete(byte[] key){
        Jedis jedis = getResource();
        try {
            jedis.del(key);
        } finally {
            jedis.close();
        }
    }

    public Set<byte[]> keys(String shiro_session_prefix){
        Jedis jedis = getResource();
        try {
            return jedis.keys((shiro_session_prefix+"*").getBytes());
        } finally {
            jedis.close();
        }
    }

}
